package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceCode;
import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.pojo.dto.PictureAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.vo.PictureStandardVO;
import cn.tedu.csmall.product.service.IPictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class PictureServiceImpl implements IPictureService {

    @Autowired
    PictureMapper pictureMapper;

    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        log.debug("开始处理图片添加业务:{}" ,pictureAddNewDTO);

        //检查是否存在相册
        int count = pictureMapper.countByAlbumId(pictureAddNewDTO.getAlbumId());
        if (count == 0){
            String message = "添加图片失败,相册[" + pictureAddNewDTO.getAlbumId() + "]不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //创建图片对象,用于插入数据
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureAddNewDTO, picture);
        picture.setWidth(1024);
        picture.setHeight(768);

        //插入数据
        int rows = pictureMapper.insert(picture);
        if (rows != 1){
            String message = "插入图片失败,服务器正在忙!请稍后再试.";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始吹删除数据");

        //查询数据是否存在
        PictureStandardVO queryResult = pictureMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除图片失败，尝试删除的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //删除图片
        int rows = pictureMapper.deleteById(id);
        if (rows != 1) {
            // 是：抛出异常(ERR_DELETE)
            String message = "删除图片失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

    }
}
